<template>
  <div>
    <div class="row wrapper border-bottom white-bg page-heading m-b-md">
      <div class="col-lg-10">
        <h2>医保地址</h2>
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>知识库管理</el-breadcrumb-item>
          <el-breadcrumb-item>医保目录管理</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </div>

    <div class="wrapper wrapper-content animated fadeInRight">
      <div class="row">
        <div class="col-lg-12">
          <div class="ibox-title page-content-header">
            <h5>检索条件</h5>
            <div class="ibox-tools">
              <button class="btn btn-danger" @click="handleShowAddModal">新增信息</button>
            </div>
          </div>
        </div>
      </div>

      <div class="row m-b">
        <div class="col-lg-12">
          <div class="ibox-content">
            <div class="row">
              <div class="col-md-3">
                <div class="form-group">
                  <label class="col-form-label" for="code">项目名称</label>
                  <el-input size="small" placeholder="请输药品或诊疗名称" v-model="searchParam.name"></el-input>
                </div>
              </div>
              <div class="col-md-2">
                <div class="form-group">
                  <label class="col-form-label" for="rate">所属省份</label>
                  <select class="form-control m-b" name="rate" v-model="searchParam.province" @change="changeProvince(searchParam.province,'search')">
                    <option value="">请选择</option>
                    <option v-for="item in data.provinceList" :value="item.categoryValue" :key="item.categoryValue">{{item.categoryName}}</option>
                  </select>
                </div>
              </div>
              <div class="col-md-2">
                <div class="form-group">
                  <label class="col-form-label" for="rate">所属市</label>
                  <select class="form-control m-b" name="rate" v-model="searchParam.city">
                    <option value="">请选择</option>
                    <option v-for="item in data.cityList" :value="item.categoryValue" :key="item.categoryValue">{{item.categoryName}}</option>
                  </select>
                </div>
              </div>
              <div class="col-md-2">
                <div class="form-group">
                  <label class="col-form-label" for="name">项目类别</label>
                  <select class="form-control m-b" name="rate" v-model="searchParam.projectType">
                    <option value="">请选择</option>
                    <option v-for="(item , index) in data.projectTypeList" :value="item.categoryValue" :key="index ">{{item.categoryName}}</option>
                  </select>
                </div>
              </div>
              <div class="col-md-2">
                <button class="btn btn-danger m-r-md m-t-lg" @click="handleGetTableData({ pageNo: 1 })"> 筛选</button>
                <button class="btn btn-reset m-r-md m-t-lg" @click="handleRest"> 重置</button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="row">
        <div class="col-lg-12">
          <div class="ibox-content edit-table clearfix">
            <el-table :data="tableData" stripe style="width: 100%" >
              <el-table-column prop="projectCode" label="项目代码" width="120">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.projectCode" :disabled="true" placeholder=""></el-input>
                </template>
              </el-table-column>
             <!--  <el-table-column show-overflow-tooltip  width="120" prop="standardName" label="标准名称" >
                <template slot-scope="scope">
                  <el-input v-model="scope.row.standardName" :disabled="true" placeholder=""></el-input>
                </template>

              </el-table-column> -->
              <el-table-column show-overflow-tooltip  prop="standardName" label="标准名称">
                                <template slot-scope="scope">
                                    <span>{{scope.row.standardName}}</span>
                                  <!--<el-input v-model="scope.row.standardName" disabled placeholder=""></el-input>-->
                                </template>
                            </el-table-column>
              <el-table-column prop="projectName" label="项目名称" width="250">
                <template slot-scope="scope">
                  <div :title="scope.row.projectName">
                    <select class="form-control" v-model="scope.row.projectName">
                      <option v-for="(item , index) in scope.row.projectNameOptions" :value="item.categoryValue" :key="item.categoryValue + index">{{item.categoryName}}</option>
                    </select>
                  </div>

                </template>
              </el-table-column>
              <el-table-column prop="indication" label="适应症" width="150">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.indication" :disabled="true" placeholder=""></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="drugSize" label="剂型" width="100">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.drugSize" :disabled="true" placeholder=""></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="province" label="所属省" width="90">
                <template slot-scope="scope">
                  <select class="form-control" v-model="scope.row.province" @change="changeProvince(scope.row.province,'table',scope.row)" :disabled="!scope.row.editable">
                    <option value="">--</option>
                    <option v-for="item in scope.row.provinceOptions" :value="item.categoryValue" :key="item.categoryValue">{{item.categoryName}}</option>
                  </select>
                </template>
              </el-table-column>
              <el-table-column prop="city" label="所属市" width="100">
                <template slot-scope="scope">
                  <select class="form-control" v-model="scope.row.city" :disabled="!scope.row.editable">
                    <option value="">--</option>
                    <option v-for="item in scope.row.cityOptions" :value="item.categoryValue" :key="item.categoryValue">{{item.categoryName}}</option>
                  </select>
                </template>
              </el-table-column>
              <el-table-column prop="drugType" label="类别" width="80">
                <template slot-scope="scope">
                  <select class="form-control" :disabled="true" v-model="scope.row.itemType">
                    <option value="">--</option>
                    <option v-for="(item , index) in data.projectTypeList" :key="index" :value="item.categoryValue">{{item.categoryName}}</option>
                  </select>
                </template>
              </el-table-column>
              <el-table-column prop="projectType" label="项目大类" width="90">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.projectType" :disabled="true" placeholder=""></el-input>
                </template>
              </el-table-column>
              <!-- <el-table-column prop="projectSubType" label="项目小类">
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.projectSubType" :disabled="!scope.row.editable" placeholder=""></el-input>
                                </template>
                            </el-table-column> -->
              <el-table-column prop="factorType" label="医保分类" width="90">
                <template slot-scope="scope">
                  <select class="form-control" :disabled="!scope.row.editable" v-model="scope.row.factorType">
                    <option value="">--</option>
                    <option v-for="item in data.matchItemClassList" :value="item.labelId" :key="item.labelId">{{item.labelName}}</option>
                  </select>
                </template>
              </el-table-column>
              <el-table-column prop="ownPay" label="自付比例" width="80">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.ownPay" :disabled="!scope.row.editable" placeholder="" @change="changeOwnPayRatio(scope.row)"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="140">
                <template slot-scope="scope">
                  <div class="btn-group btn-group-toggle handle-button" data-toggle="buttons">
                    <div class="btn btn-white btn-xxs" :class="['btn btn-white btn-xxs', scope.row.editable ? 'hide':'']">
                      <a href="#" @click="showSynonyms(scope.row)"> 别名 </a>
                    </div>
                    <div :class="['btn btn-white btn-xxs', scope.row.editable ? 'hide':'']" @click="handleEdit(scope.row)">
                      <a href="#"> 编辑 </a>
                    </div>
                    <div :class="['btn btn-white btn-xxs save-tr', scope.row.editable ? '':'hide']" @click="handleSave(scope.row)">
                      <a href="#"> 保存 </a>
                    </div>
                    <div :class="['btn btn-white btn-xxs cancel-tr' , scope.row.editable ? '':'hide']" @click="handleCancel(scope.row)">
                      <a href="#"> 取消 </a>
                    </div>
                    <div :class="['btn btn-white btn-xxs cancel-tr' , scope.row.editable ? 'hide':'']" @click="handleDelete(scope.row)" v-show="scope.row.id !== null && scope.row.id !== ''">
                      <a href="#"> 删除 </a>
                    </div>
                  </div>
                </template>
              </el-table-column>

            </el-table>
            <div class="pagination">
              <el-pagination background layout="prev, pager, next" :current-page.sync="pagination.currentPage" :page-size="pagination.size" :total="pagination.total" @current-change="handleCurrentChange">
              </el-pagination>
            </div>

          </div>

        </div>
      </div>
    </div>

    <div v-if="synonymsData.state">
      <Synonyms :synonyms-data="synonymsData" v-on:hide-dialog="hideDiolog"></Synonyms>
    </div>

    <el-dialog title="新增信息" :visible.sync="addMedical.dialogVisible" class="ackonwledge-codeList-add">
      <el-form :model="addMedical">
        <div>
          <span class="label-name">检索条件</span>
          <el-input v-model="addMedical.searchCon" auto-complete="off"></el-input>
          <el-button type="primary" @click="handleAddModalGetSeachResult">检索</el-button>
        </div>

        <div>
          <span class="label-name">检索结果</span>
          <select class="form-control m-b" v-model="addMedical.searchResult">
            <option value="">请选择</option>
            <option v-for="(item , index) in addMedical.searchResultList" :value="item.categoryValue" :key="index ">{{item.categoryName}}</option>
          </select>
        </div>

        <div>
          <span class="label-name">所属省</span>
          <select class="form-control m-b" v-model="addMedical.province" @change="changeProvince(addMedical.province , 'addMedical')">
            <option value="">请选择</option>
            <option v-for="(item , index) in data.provinceList" :value="item.categoryValue" :key="index ">{{item.categoryName}}</option>
          </select>
        </div>

        <div>
          <span class="label-name">所属市</span>
          <select class="form-control m-b" v-model="addMedical.city">
            <option value="">请选择</option>
            <option v-for="(item , index) in addMedical.cityOptions" :value="item.categoryValue" :key="index ">{{item.categoryName}}</option>
          </select>
        </div>

        <div>
          <span class="label-name">比例</span>
          <el-input v-model="addMedical.ratio" auto-complete="off"></el-input>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addMedical.dialogVisible = false">返 回</el-button>
        <el-button type="primary" :disabled="addMedical.searchResult === ''" @click="handleAdd(addMedical)">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import _ from "lodash";
import {  Basic, } from "@/assets/js/api";


export default {
  name: "ackonwledge_codeList",
  data: function() {
    return {
      searchParam: {
        name: "",
        province: "",
        city: "",
        projectType: ""
      },
      tableData: [],
      synonymsData: {
        title: {
          titleName: "",
          standardName: ""
        },
        thName: "",
        data: null,
        state: false
      },
      pagination: {
        currentPage: 1,
        size: 10,
        total: 0
      },
      data: {
        provinceList: [],
        cityList: [],
        projectTypeList: [],
        matchItemClassList: DefaultConst.MatchItemClassList
      },
      edit: {
        state: false,
        data: {}
      },
      addMedical: {
        dialogVisible: false,
        searchCon: "",
        searchResult: "",
        searchResultList: [],
        province: "",
        city: "",
        cityOptions: [],
        ratio: ""
      }
    };
  },
  created() {
    this.getIninalData();
  },
  mounted() {},
  computed: {},
  methods: {
    getIninalData() {
      Promise.all([Basic.getProvince(), Basic.getCode({ type: "CS0009" })])
        .then(([provinceRes, projectTypeRes]) => {
          if (provinceRes && provinceRes.data) {
            this.data.provinceList = provinceRes.data.map(item => {
              return {
                categoryName: item.regionName,
                categoryValue: item.regionId
              };
            });
          }

          if (projectTypeRes && projectTypeRes.data) {
            this.data.projectTypeList = projectTypeRes.data.map(item => {
              return {
                categoryName: item.labelName,
                categoryValue: item.labelValue
              };
            });
          }
        })
        .catch(() => {});
    },
    showSynonyms: _.debounce(function(data) {
      let _this = this;
      let callback = function() {
        _this.synonymsData = {
          title: {
            titleName: "标准名称",
            standardName: data.standardName
          },
          thName: _this.data.projectTypeList.map(item => {
            return data.itemType == Number(item.categoryValue)
              ? item.categoryName
              : "";
          }),
          data: data,
          type: "medical",
          state: true
        };
      };

      if (!this.edit.state) {
        callback();
      } else {
        this.handleHasEditRow(callback);
      }
    }, 500),
    hideDiolog() {
      this.synonymsData.state = false;
    },
    handleEdit: _.debounce(function(data) {
      let _this = this;
      let callback = function() {
        let obj = {
          factorType: data.factorType,
          ownPay: data.ownPay,
          province: data.province,
          city: data.city,
          cityOptions: data.cityOptions
        };
        _this.edit.state = true;
        _this.edit.data = _.cloneDeep(obj);

        data.editable = true;
      };

      if (!this.edit.state) {
        callback();
      } else {
        this.handleHasEditRow(callback);
      }
    }, 500),
    handleCancel(data) {
      this.$confirm("确认放弃修改吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        confirmButtonClass: "confirmButtonClass"
      })
        .then(() => {
          this.handleCancelRow(data);
        })
        .catch(() => {});
    },
    handleCancelRow(data) {
      data.editable = false;
      data.factorType = this.edit.data.factorType;
      data.ownPay = this.edit.data.ownPay;
      data.province = this.edit.data.province;
      data.city = this.edit.data.city;
      data.cityOptions = this.edit.data.cityOptions;

      this.edit.state = false;
      this.edit.data = {};
    },
    handleSave: _.debounce(function(data) {
      if (
        data.province === "" ||
        data.province === null ||
        data.city === "" ||
        data.city === null
      ) {
        this.$alert("--省份与城市", "提示", {
          confirmButtonText: "确定",
          confirmButtonClass: "confirmButtonClass"
        });
        return;
      }

      let _data = {
        chargeItemCode: data.projectCode ? data.projectCode : null,
        chargeItemName: data.projectName ? data.projectName : null,
        provinceId: data.province,
        provinceName:
          data.province !== "" &&
          data.provinceOptions.find(
            item => item.categoryValue === data.province
          )
            ? data.provinceOptions.find(
                item => item.categoryValue === data.province
              ).categoryName
            : "",
        regionId: data.city,
        regionName:
          data.city !== "" &&
          data.cityOptions.find(item => item.categoryValue === data.city)
            .categoryName
            ? data.cityOptions.find(item => item.categoryValue === data.city)
                .categoryName
            : "",
        ratio: data.ownPay
      };
      if (data.id !== null) {
        Ackonwledge.Medical.save({
          ..._data,
          id: data.id
        }).then(response => {
          if (response && response.data) {
            data.editable = false;
            this.edit.state = false;
            this.$alert("保存成功", "提示", {
              confirmButtonText: "确定",
              confirmButtonClass: "confirmButtonClass"
            });
          }
        });
      } else {
        Ackonwledge.Medical.add(_data)
          .then(response => {
            if (response && response.data !== null) {
              data.id = response.data;
              data.editable = false;
              this.edit.state = false;
              this.$alert("保存成功", "提示", {
                confirmButtonText: "确定",
                confirmButtonClass: "confirmButtonClass"
              });
            }
          })
          .catch(() => {});
      }
    }, 500),
    handleDelete: _.debounce(function(data) {
      let _this = this;
      let callback = function() {
        _this
          .$confirm(`确认删除${data.standardName}吗?`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            confirmButtonClass: "confirmButtonClass"
          })
          .then(() => {
            Ackonwledge.Medical.delete({ id: data.id })
              .then(response => {
                if (response && response.data) {
                  _this.$alert("删除成功", "提示", {
                    confirmButtonText: "确定",
                    confirmButtonClass: "confirmButtonClass",
                    callback: action => {
                      
                    }
                  });
                }
              })
              .catch(() => {});
          })
          .catch(() => {});
      };

      if (!this.edit.state) {
        callback();
      } else {
        this.handleHasEditRow(callback);
      }
    }, 500),
    handleShowAddModal() {
      this.addMedical.dialogVisible = true;
    },
    handleAddModalGetSeachResult: _.debounce(function(row) {
      let data = this.addMedical.searchCon;
      if (data && data !== "") {
        Intelligent.searchTaskOptions({
          matchType: 3,
          itemName: data
        })
          .then(response => {
            if (response && response.data.length > 0) {
              this.addMedical.searchResultList =
                response &&
                response.data &&
                response.data.map(res => {
                  return {
                    categoryName: res.matchItemName,
                    categoryValue: res.matchItemId
                  };
                });
            }

            if (response && response.data.length === 0) {
              this.addMedical.searchResultList = [];
            }
          })
          .catch(() => {});
      }
    }, 500),
    handleAdd(data) {
      // let data = this.addMedical;
      if(this.addMedical.ratio < 0 ||this.addMedical.ratio > 1){
        this.$alert('比例应该控制在0-1之间')
      }else{
        Ackonwledge.Medical.add({
        chargeItemCode: data.searchResult !== "" ? data.searchResult : null,
        chargeItemName:
          data.searchResultList.length > 0 && data.searchResult !== ""
            ? data.searchResultList.find(
                item => item.categoryValue === data.searchResult
              ).categoryName
            : null,
        provinceId: data.province,
        provinceName:
          data.province !== "" &&
          this.data.provinceList.find(
            item => item.categoryValue === data.province
          )
            ? this.data.provinceList.find(
                item => item.categoryValue === data.province
              ).categoryName
            : "",
        regionId: data.city,
        regionName:
          data.city !== "" &&
          data.cityOptions.find(item => item.categoryValue === data.city)
            .categoryName
            ? data.cityOptions.find(item => item.categoryValue === data.city)
                .categoryName
            : "",
        ratio: data.ratio
      })
        .then(response => {
          if (response.meta.code === "200" && response.data) {
            
            // this.addMedical.dialogVisible = false;
            this.$alert("新增成功", "提示", {
              confirmButtonText: "确定",
              confirmButtonClass: "confirmButtonClass"
            });
          }
        })
        .catch(() => {});
      }
      
    },
    handleCurrentChange(val) {
      this.handleGetTableData({ pageNo: val });
    },
    handleRest() {
      this.searchParam.name = "";
      this.searchParam.province = "";
      this.searchParam.city = "";
      this.searchParam.cityList = [];
      this.searchParam.projectType = "";
     
    },
    handleGetTableData: _.debounce(function({ pageNo }) {
      let _this = this;
      let callback = function() {
        Ackonwledge.Medical.getList({
          pageNum: pageNo,
          pageSize: _this.pagination.size,
          chargeItemNameSyn: _this.searchParam.name.trim(""),
          regionId: _this.searchParam.city,
          chargeItemType: _this.searchParam.projectType
        })
          .then(response => {
            if (response && response.data && response.data.length > 0) {
              _this.tableData = response.data.map(item => {
                return _this.filterTableRow(item);
              });

              _this.pagination.currentPage = pageNo;
              _this.pagination.total = response.meta.total;
            }
            if (response && response.data && response.data.length === 0) {
              _this.tableData = [];
            }
          })
          .catch(() => {});
      };

      if (!this.edit.state) {
        callback();
      } else {
        this.handleHasEditRow(callback);
      }
    }, 500),
    filterTableRow(item) {
      return {
        id: item.id,
        projectCode: item.chargeItemCode, //项目代码
        standardName: item.chargeItemName, //标准名称
        projectName:
          item.chargeItemNameSyns &&
          item.chargeItemNameSyns.length > 0 &&
          item.chargeItemNameSyns[0].chargeItemNameSyn, //项目名称
        projectNameOptions:
          item.chargeItemNameSyns &&
          item.chargeItemNameSyns.map(d => {
            return {
              categoryName: d.chargeItemNameSyn,
              categoryValue: d.chargeItemNameSyn
            };
          }),
        indication: item.indication !== null ? item.indication : "", //适应症
        drugSize: item.dosageForm !== null ? item.dosageForm : "", //剂型
        province: item.provinceId !== null ? item.provinceId : "", //所属省份
        provinceOptions: this.data.provinceList,
        city: item.regionId !== null ? item.regionId : "", //所属地区
        cityOptions:
          item.regionId !== null && item.regionName
            ? [
                {
                  categoryName: item.regionName,
                  categoryValue: item.regionId
                }
              ]
            : [],
        itemType: item.chargeItemType !== null ? item.chargeItemType : "", //类别    -----------
        projectType: item.itemType !== null ? item.itemType : "", //项目大类
        projectSubType: item.itemType !== null ? item.itemType : "", //项目小类  --------------------
        factorType:
          item.ratio !== null ? this.getInsuranceType(item.ratio) : "", //医保分类
        ownPay: item.ratio !== null ? item.ratio : "", //自付比例
        //   daleiInfo: "西药费", //大类信息
        editable: false
      };
    },
    changeOwnPayRatio(data) {
      if (data.ownPay !== "" && !isNaN(data.ownPay)) {
        data.factorType = this.getInsuranceType(data.ownPay);
      } else {
        data.factorType = "";
      }
    },
    changeProvince(province, type, selectedRow) {
      if (province != "") {
        Basic.getCity({ parentId: province })
          .then(response => {
            if (response && response.data) {
              let selectOptions = response.data.map(item => {
                return {
                  categoryName: item.regionName,
                  categoryValue: item.regionId
                };
              });

              if (type === "search") {
                this.data.cityList = selectOptions;
              }

              if (type === "table") {
                selectedRow.cityOptions = selectOptions;
              }

              if (type === "addMedical") {
                this.addMedical.cityOptions = selectOptions;
              }
            }
          })
          .catch(() => {});
      }
    },
    getInsuranceType(ratio) {
      let _ratio = Number(ratio);
      if (_ratio > 0 && _ratio < 1) {
        return 2;
      }
      if (Math.ceil(_ratio) === 0) {
        return 1;
      }
      if (Math.ceil(_ratio) === 1) {
        return 3;
      }
    },
    handleHasEditRow(callback) {
      this.$confirm("是否放弃修改的数据", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        confirmButtonClass: "confirmButtonClass"
      })
        .then(() => {
          let editRow = this.tableData.filter(item => item.editable)[0];
          this.handleCancelRow(editRow);
          callback();
        })
        .catch(() => {});
    }
  }
};
</script>

<style>
.ackonwledge-codeList-add .el-input,
.ackonwledge-codeList-add .form-control {
  width: calc(80% - 60px);
  margin: 5px 15px;
  display: inline-block;
}
.ackonwledge-codeList-add .el-input__inner {
  height: 32px;
  line-height: 32px;
}
.ackonwledge-codeList-add .el-button--primary {
  border-color: #fe5d3c;
  background-color: #fe5d3c;
}
.ackonwledge-codeList-add .label-name {
  font-size: 13px;
  display: inline-block;
  width: 60px;
  text-align: right;
}
</style>
